<?php
//require_once  __DIR__ . '/includes/authenticate.php';

if (isset($_POST['opponentteamID']) && isset($_POST['location']) && isset($_POST['date']) && $_POST['date'] != '' && $_POST['opponentteamID'] != $_POST['coachteamID'] ) {

	require_once __DIR__ . './../../includes/BasketbalFunctions.php';
	$basketbalfunctions = new BasketbalFunctions();

	require_once __DIR__ . '/db_connect_basketbal.php';

	$opponentteamID = $_POST['opponentteamID'];
	$opponentteamname = $basketbalfunctions->GetTeamNameFromTeamID($opponentteamID);
	$coachteamID = $_POST['coachteamID'];
	$gamedate = $_POST['date'];
	$gametype = $_POST['gametype'];
	$location = $_POST['location'];
	$season = $_POST['season'];

	// check if game already exists
	$sql = "SELECT COUNT(*) FROM games_list WHERE teamID_home = :teamhomeID AND teamID_away = :teamawayID AND date = :gamedate ";
	$stmt = $db->prepare($sql);
	if ($location == "home") {
			$stmt->bindParam(':teamhomeID', $coachteamID);
			$stmt->bindParam(':teamawayID', $opponentteamID);
	} else {
			$stmt->bindParam(':teamhomeID', $opponentteamID);
			$stmt->bindParam(':teamawayID', $coachteamID);
	}

	$stmt->bindParam(':gamedate', $gamedate);
	$stmt->execute();

	if ($stmt->fetchColumn() != 0) {
		echo "This game already exists.";
	} else {
		try {	
				$gameID = hash('crc32', microtime(true). mt_rand().$coachteamID);
				$sql = "INSERT INTO games_list (gameID, teamID_home, teamID_away, type, date) VALUES (:gameID,:teamhomeID,:teamawayID, :gametype, :gamedate)";
				$stmt = $db->prepare($sql);
				$stmt->bindParam(':gameID', $gameID);
				if ($location == "home") {
						$stmt->bindParam(':teamhomeID', $coachteamID);
						$stmt->bindParam(':teamawayID', $opponentteamID);
				} else {
						$stmt->bindParam(':teamhomeID', $opponentteamID);
						$stmt->bindParam(':teamawayID', $coachteamID);
				}
				$stmt->bindParam(':gametype', $gametype);
				$stmt->bindParam(':gamedate', $gamedate);
				$stmt->execute();

				include_once './db_bb_connect.php';

				$sql = "INSERT INTO games (gameID, season, date, opponent, opponent_teamID, location)
				VALUES ('$gameID','$season','$gamedate','$opponentteamname','$opponentteamID','$location')";

				if ($db->query($sql)) {
					echo "<br><center><strong>Game has been succesfully added to games old! </strong></center>";
				} else {
					echo "<br><center>Error: " . $sql . "<br>" . $db->error . "</center>";
				}

				if ($stmt->rowCount()) {
					echo "<br><center><strong>Game has been succesfully added to games new! </strong></center>";
					exit;
				}

				
			} catch (\PDOException $e){
				if (0 === strpos($e->getCode(),'23')) {
					$gameID = hash('crc32', microtime(true). mt_rand().$teamhomeID);
					if (!$stmt->execute()) {
						throw $e;
					}
				}
			}

		}
	} elseif ($_POST['date'] == ''){
		echo "No date entered";
	} elseif ($_POST['teamhomeID'] == $_POST['teamawayID']) {
		echo "A Game between the same 2 teams is not possible";
	}


?>

